declare boundary-space preserve;
declare option xdmp:mapping "false";

let $action := xdmp:get-request-field("submit")
let $name := xs:string(xdmp:get-request-field("name"))
let $username := xs:string(xdmp:get-request-field("username"))
let $email := xs:string(xdmp:get-request-field("email"))
let $address1 := xs:string(xdmp:get-request-field("address1"))
let $address2 := xs:string(xdmp:get-request-field("address2"))
let $city := xs:string(xdmp:get-request-field("city"))
let $state := xs:string(xdmp:get-request-field("state"))
let $zip := xs:string(xdmp:get-request-field("zip"))
let $phone := xs:string(xdmp:get-request-field("phone"))
let $active := xdmp:get-request-field("active")
let $id := xs:string(xdmp:get-request-field("id"))
let $id := if(fn:string-length($id)>0)then $id else xdmp:random()
let $uri := fn:concat("/affiliates/", $id, ".xml")

let $new := 
		<affiliate affiliateid="{$id}">
					<name>{$name}</name>
					<username>{$username}</username>
					<email>{$email}</email>
					<rate>{0}</rate>
					<address>
						<line>{$address1}</line>
						<line>{$address2}</line>
						<city>{$city}</city>
						<state>{$state}</state>
						<zip>{$zip}</zip>
					</address>
					<phone>{$phone}</phone>
					<affiliateStates>
						{if($active)then<affiliateState id="active"/>else()}
					</affiliateStates>
					<lastPaid>{}</lastPaid>
		</affiliate>
	
		
let $doaction :=

	if ($action="Save") then xdmp:document-insert($uri, $new)
	else if ($action="Remove") then xdmp:document-delete($uri)
	else ()
return xdmp:redirect-response("/backoffice/affiliates?msg=Saved")
